package net.yxsoft.service.infrastructure;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import net.yxsoft.enumclass.LockEnumCls;
import net.yxsoft.model.infrastructure.TsDatamodelProperties;
import net.yxsoft.model.infrastructure.TsParty;
import net.yxsoft.model.infrastructure.TsUdmkey;
import rapid.core.Authuser;
import rapid.core.ContextStateEnum;
import rapid.core.TResult;
import rapid.jfinal.BaseService;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/6/12.
 */

public class UDMKeyService extends BaseService {

  /**
  * @MethodName: getDataModelUDMKeyList
  * @Description: 
  * @param: modelId
   * @param: name
  * @return * @return java.util.List<com.jfinal.plugin.activerecord.Record>
  * @throws 
  * @date 2023/8/31 13:33
  * @author wj 
  */
  public static List<Record> getDataModelUDMKeyList(String modelId, String name) {
    StringBuffer sql = new StringBuffer();

    String _state = LockEnumCls.LOCKED.getValue();

    TsParty _party = TsParty.dao.findById(modelId);







    sql.append(String.format("select id as value,attrib_name,attrib_descn,\n" +
                 "( case when nullif(attrib_descn,'')='' then attrib_name\n" +
                 "else concat(attrib_descn,concat('|',attrib_name)) end ) as text\n" +
                 " from ts_datamodel_properties\n" +
                 "where model_id=? and  state='%s' ",_state));
    if(StrKit.notBlank(name)) {
      sql.append(String.format(" and locate('%s',attrib_name) or locate('%s',attrib_descn)", name, name));
    }

    if(_party != null){
      if("FN_FORM_DATA".equals(_party.getName())){
        sql.append(" and attrib_name <> 'ATTRIB_01' ");
      }
    }

    sql.append(" order by id");

    return Db.find(sql.toString(), modelId);
  }
  
  /**
  * @MethodName: saveUDMKey
  * @Description: 新增主键
  * @param: modelId
   * @param: title
   * @param: attribs
   * @param: sessionUser
  * @return * @return rapid.core.TResult
  * @throws
  * @date 2023/8/31 13:33
  * @author wj
  */
  public static TResult saveUDMKey(String modelId, String title, String attribs, Authuser sessionUser) {
    TResult rt = new TResult();
    rt.setState(ContextStateEnum.FAIL);
    Timestamp time = new Timestamp(new Date().getTime());
    if(StrKit.isBlank(modelId)) {
      rt.setMessage("模型为空，保存失败！");
      return rt;
    }
    TsParty _modelParty = TsParty.dao.findById(modelId);
    if(null == _modelParty) {
      rt.setMessage("该数据模型不存在！");
      return rt;
    }
    if(StrKit.isBlank(attribs)) {
      rt.setMessage("请选择字段类型！");
      return rt;
    }
    List<TsDatamodelProperties> list = TsDatamodelProperties.dao.find(String.format("select * from ts_datamodel_properties where id in (%s) and model_id=%s and state='1' order by id ", attribs, modelId));
    if(null == list || list.size() == 0) {
      rt.setMessage("请选择字段类型！");
      return rt;
    }
    StringBuffer attribType = new StringBuffer();
    StringBuffer attribDesc = new StringBuffer();
    for(TsDatamodelProperties p : list) {
      if(StrKit.notBlank(p.getAttribName())) {
        attribType.append(p.getAttribName() + "|");
      }
      if(StrKit.notBlank(p.getAttribDescn())) {
        attribDesc.append(p.getAttribDescn() + "|");
      }

    }
    String attribtype = attribType.toString();
    String attribdesc = attribDesc.toString();
    if(StrKit.notBlank(attribtype) && attribtype.indexOf("|") > 0) {
      attribtype = attribtype.substring(0, attribtype.lastIndexOf("|"));
      //判断主键组合是否已存在
      TsUdmkey udKey = TsUdmkey.dao.findFirst("select * from ts_udmkey where attrib_02=? and row_id=? ", attribtype, modelId);
      if(null != udKey) {
        rt.setMessage("该组合主键已存在！");
        return rt;
      }
    } else {
      rt.setMessage("请选择字段类型！");
      return rt;
    }
    if(StrKit.notBlank(attribdesc) && attribdesc.indexOf("|") > 0) {
      attribdesc = attribdesc.substring(0, attribdesc.lastIndexOf("|"));
    }

    TsUdmkey _model = new TsUdmkey();
    if(!"100".equals(_modelParty.getParPartyId())) {
      _model.setParRowId(Integer.parseInt(_modelParty.getParPartyId()));
    }
    _model.setRowId(Integer.parseInt(modelId));
    _model.setCreated(time);
    _model.setCreatedBy(sessionUser.getId());
    _model.setLastUpd(time);
    _model.setLastUpdBy(sessionUser.getId());
    _model.setAttrib01(title);   //标题
    _model.setAttrib02(attribtype);//主键 字段属性 | 分割
    _model.setAttrib03(attribdesc); //字段说明
    boolean _r = _model.save();
    if(_r) {
      //保存成功
      rt.setMessage("添加成功！");
      rt.setState(ContextStateEnum.SUCCESS);
      return rt;
    } else {
      //保存失败
      rt.setMessage("添加失败！");
      return rt;
    }
  }

  /**
  * @MethodName: removeUDMKey
  * @Description: 
  * @param: ids
  * @return * @return rapid.core.TResult
  * @throws 
  * @date 2023/8/31 14:05
  * @author wj 
  */
  public static TResult removeUDMKey(String ids) {
    TResult rt = new TResult();
    rt.setState(ContextStateEnum.FAIL);
    if(StrKit.isBlank(ids)) {
      rt.setMessage("请选择需要删除的数据！");
      return rt;
    }

    String[] _ids = ids.split(",");

    try {
      for(int i = 0; i < _ids.length; i++) {
        TsUdmkey.dao.deleteById(_ids[i]);
      }

      rt.setMessage("删除成功！");
      rt.setState(ContextStateEnum.SUCCESS);
    }catch(Exception ex) {
      rt.setMessage("删除失败！");
    }
    return rt;

  }

}
